<template>
  <n-grid cols="24" x-gap="10" item-responsive responsive="screen">
    <n-grid-item span="24 m:24 l:24">
      <n-space :wrap-item="false">
        <n-card
          :segmented="{ content: true, footer: 'soft' }"
          header-style="font-size:14px;"
          title="编辑角色信息"
        >
          <template #header-extra>修改</template>
          <n-form
            ref="formRef"
            :model="compData.from"
            :rules="compData.rules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="角色名" path="name">
              <n-input
                v-model:value="compData.from.name"
                placeholder="请输入角色名"
              />
            </n-form-item>
            <n-form-item label="菜单权限" path="menuIds">
              <n-select
                v-model:value="compData.from.menuIds"
                multiple
                :options="menuOptions"
                placeholder="请选择菜单权限"
              />
            </n-form-item>
            <n-form-item label="图片权限" path="picAuth">
              <n-radio-group v-model:value="compData.from.picAuth" name="picAuth">
                <n-space>
                  <n-radio v-for="pa in picAuthOptions" :key="pa.value" :value="pa.value">
                    {{ pa.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="是否默认角色" path="is_default">
              <n-checkbox
                v-model:checked="compData.from.is_default"
                checked-value="1"
                unchecked-value="0"
              >
                默认角色
              </n-checkbox>
            </n-form-item>
          </n-form>
          <template #action>
            <n-space justify="end">
              <n-button attr-type="button" @click="$router.back()">返回列表</n-button>
              <n-button
                attr-type="button"
                type="success"
                @click="submit"
                >提交数据</n-button
              >
            </n-space>
          </template>
        </n-card>
      </n-space>
    </n-grid-item>
  </n-grid>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { FormInst, NSpace, NCard, NForm, NFormItem, NInput, NSelect, NRadioGroup, NRadio, NButton, NCheckbox } from "naive-ui";
import { updateRole, getRoleList } from "@/app/admin/api/role.ts";
import { useRoute, useRouter } from "vue-router";
import { getOneLevelMenusList } from "@/app/admin/api/menu.ts";
import { picAuthOptions } from "./data";
import XEUtils from "xe-utils";


const formRef = ref<FormInst | null>(null);
const router = useRouter();
const route = useRoute();

const menuOptions = ref([]);

const compData = reactive({
  from: {
    name: null,
    menuIds: null,
    picAuth: null,
    is_default: "0",
  },
  rules: {
    name: {
      required: true,
      trigger: ["blur", "input"],
      message: "请输入角色名",
    },
    menuIds: {
      type: "array",
      required: true,
      trigger: ["blur", "change"],
      message: "请选择菜单权限",
    },
    picAuth: {
      required: true,
      trigger: ["blur", "change"],
      message: "请选择图片权限",
    },
  },
});

// 提交数据
const submit = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      const role = XEUtils.clone(compData.from, true);
      role.menuIds = role.menuIds.join(",");
      updateRole(Object.assign({ rid: route.params.id }, role))
        .then((res: any) => {
          if (res.status === "success") {
            window.$message.success("修改成功");
            router.back();
          } else {
            window.$message.error("修改失败");
          }
        });
    } else {
      window.$message.warning("请填写必填项");
    }
  });
};

onMounted(async () => {
  const res: any = await getOneLevelMenusList();
  menuOptions.value = res.data || [];
  if (route.params.id === ":id") return;
  const _params = {
    pageSize: 10,
    pageNumber: 1,
    rid: route.params.id,
  };
  getRoleList(_params).then((res: any) => {
    const data = (res.data?.list || []).filter(
      (item: any) => item.rid === route.params.id
    )?.[0] || {};
    Object.keys(compData.from).forEach((key) => {
      if (["menuIds"].includes(key)) {
        compData.from[key] = data[key]?.split(",") || [];
      } else {
        compData.from[key] = data[key];
      }
    });
  });
});
</script>
